from pywinauto import Desktop, Application
from pywinauto.findwindows import WindowNotFoundError, ElementNotFoundError
import argparse
import time
import sys


class ClockAndAlarm(object):
    def __init__(self):
        # launch App and make sure it is in Timer tab
        self.app = Application(backend="uia")
        try:
            self.window = self.app.connect(title="闹钟和时钟").window()
        except ElementNotFoundError:
            print("window not found. Try launch apps.")
            self.app = self.app.start('explorer.exe "shell:Appsfolder\Microsoft.WindowsAlarms_8wekyb3d8bbwe!App"')
            time.sleep(1)
            self.window = self.app.connect(title="闹钟和时钟").window()
        self.window.window(auto_id="TimerButton", control_type="ListItem").wrapper_object().select()
        self.default_timers = ['番茄-工作', '番茄-休息', '番茄-大休息']


    def start_timer(self, timer):
        if timer not in self.default_timers:
            print('make sure this time really exists.')
        start = self.window[timer + 'Static'].wrapper_object().parent().children()[1]
        # assert start.texts()[0] == ['开始'] and len(start.texts()) == 1
        start.click()


    def stop_all(self, reset=False):
        timer_list = self.window.window(auto_id="TimerListView").wrapper_object().items()
        for timer in timer_list:
            if '正在运行' in ''.join(timer.children()[1].texts()):
                timer.children()[1].click()
                print(''.join(timer.children()[3].texts()))
            if reset and timer.children()[0].is_enabled():
                timer.children()[0].click()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Process')
    # parser.add_argument('timer', required=False)
    parser.add_argument('--start', '-s',
                        help='start timer')
    parser.add_argument('--stop-all', action='store_true',
                        help='stop all timers')
    parser.add_argument('--reset-all', action='store_true',
                        help='reset all timers')

    args = parser.parse_args()
    # print(args)
    if args.stop_all or args.reset_all or args.start is not None:
        app = ClockAndAlarm()
    else:
        sys.exit(0)
    if args.stop_all:
        app.stop_all()
    if args.reset_all:
        app.stop_all(reset=True)
    if args.start is not None:
        app.start_timer(timer=args.start)